package com.yjymm.edu.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjymm.edu.common.CommonResultUtils;
import com.yjymm.edu.common.component.OSSComponent;
import com.yjymm.edu.mapper.OrderEvaluateMapper;
import com.yjymm.edu.model.common.CommonResult;
import com.yjymm.edu.model.dto.OrderEvaluateDTO;
import com.yjymm.edu.model.entity.OrderEvaluate;
import com.yjymm.edu.model.entity.OrderTable;
import com.yjymm.edu.service.OrderEvaluateService;
import com.yjymm.edu.service.OrderTableService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yjymm
 * @since 2021-01-30
 */
@Service
public class OrderEvaluateServiceImpl extends ServiceImpl<OrderEvaluateMapper, OrderEvaluate> implements OrderEvaluateService {

    @Resource
    private OSSComponent ossComponent;

    @Resource
    private OrderTableService orderTableService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(OrderEvaluateDTO dto) throws Exception {
        // 修改订单状态
        OrderTable orderTable = new OrderTable();
        orderTable.setId(dto.getOid());
        orderTable.setFinished(3);
        orderTableService.saveOrUpdate(orderTable);
        // 插入订单评价
        OrderEvaluate orderEvaluate = new OrderEvaluate();
        orderEvaluate.setOid(dto.getOid());
        orderEvaluate.setStar(dto.getScore());
        orderEvaluate.setDescription(dto.getDescription());
        String imgs = "";
        if (!CollectionUtils.isEmpty(dto.getImgNames())) {
            for (int i = 0; i < dto.getImgNames().size(); i++) {
                imgs += dto.getImgNames().get(i);
                if (i != dto.getImgNames().size() - 1) {
                    imgs += ";";
                }
            }
        }
        orderEvaluate.setImgs(imgs);
        baseMapper.insert(orderEvaluate);
    }

    @Override
    public CommonResult uploadImg(MultipartFile multipartFile) throws Exception {
        String filename = multipartFile.getOriginalFilename();
        ossComponent.uploadFile(multipartFile.getInputStream(), filename);
        return CommonResultUtils.build(filename);
    }
}
